package com.vxfly.helioscamera.Activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.vxfly.helioscamera.SDKAPI.CameraProperties;
import com.vxfly.helioscamera.Tool.ConfigureInfo;
import com.vxfly.helioscamera.Tool.CrashHandler;
import com.vxfly.helioscamera.Tool.FileTools;
import com.vxfly.helioscamera.adapter.CameraSlotAdapter;
import com.vxfly.helioscamera.baseItems.CameraSelectedInfo;
import com.vxfly.helioscamera.baseItems.WifiSsidPwd;
import com.vxfly.helioscamera.camera.MyCamera;
import com.vxfly.helioscamera.function.ActivityCollector;
import com.vxfly.helioscamera.function.CameraSlotSQLite;
import com.vxfly.helioscamera.function.SystemCheckTools;
import com.vxfly.helioscamera.function.ThumbnailOperation;
import com.vxfly.helioscamera.function.UserMacPermition;
import com.vxfly.helioscamera.function.WifiCheck;
import com.vxfly.helioscamera.global.App.CameraSlot;
import com.vxfly.helioscamera.global.App.ExitApp;
import com.vxfly.helioscamera.global.App.GlobalInfo;
import com.vxfly.helioscamera.global.App.PropertyId;
import com.vxfly.helioscamera.global.sdk.SDKEvent;
import com.vxfly.helioscamera.global.sdk.SDKSession;
import com.vxfly.helioscamera.log.WriteLogToDevice;
import com.vxfly.helioscamera.R;
import com.icatch.wificam.customer.ICatchWificamListener;
import com.icatch.wificam.customer.ICatchWificamLog;
import com.icatch.wificam.customer.ICatchWificamSession;
import com.icatch.wificam.customer.exception.IchListenerExistsException;
import com.icatch.wificam.customer.type.ICatchEvent;
import com.icatch.wificam.customer.type.ICatchEventID;
import com.icatch.wificam.customer.type.ICatchLogLevel;

public class AppStartActivity extends Activity {
	private final String TAG="AppStartActivity";
	public static final int CONNECT_SUCCESS = 0;
	public static final int CONNECT_FAIL = 1;
	public static final int CONNECT_RETRY = 2;
	public static final int CONNECT_NEW_WIFI_SUCCESS = 3;
	public static final int CONNECT_NEXT_WIFI = 4;
	public static final int NO_WIFI_CONNECTTED = 5;
	public static final int CONNECTING = 6;
	private List<ScanResult> wifiList = null;
	private int reconnectTime = 0;
	private static final int RETRY_TIMES = 6;
	private WifiCheck wifiCheck;
	private ScanResult cfgConvertWifi = null;
	private SDKEvent sdkEvent;
	private LinkedList<SelectedCameraInfo> searchCameraInfoList;
	protected ScanCameraListener scanCameraListener;
	// private SQLiteOperate mySQLite;
	private SQLiteDatabase db;
	private List<CameraSlot> camSlotList;
	private ListView camSlotListView;
	private CameraSlotAdapter myListViewAdapter;
	private CameraSlotSQLite mySQLite;

	// End add by zhangyanhu 2013.11.27


//	private final String strWifiSSID="Airbot_Ground_445";
	private final String strWifiSSID="Aibao_Ground_2043";
	private final String strWifiPwd="1234567890";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "AppStart onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.start);

		// never sleep when run this activity
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		// do not display menu bar
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		//WriteLogToDevice.initConfiguration();// configure the app log default
		// catch the android exception for app and record it as file
		CrashHandler.getInstance().init(AppStartActivity.this);
		CameraSlotSQLite.getInstance().creatTable(this);
		ConfigureInfo.readCfgInfo(AppStartActivity.this);
		// set
		if (GlobalInfo.saveSDKLog) {
			enableSDKLog();
		}
		if(GlobalInfo.saveAPPLog){
			WriteLogToDevice.initConfiguration();
		}
	
//		enableSDKLog();
//		WriteLogToDevice.initConfiguration();
		
		GlobalInfo.getInstance().setCurrentApp(AppStartActivity.this);

		// JIRA ICOM-1890 Begin:Delete by zhangyanhu C01012 2015-08-27
		// ExitApp.getInstance().addActivity(this);
		// JIRA ICOM-1890 End:Delete by zhangyanhu C01012 2015-08-27

		// JIRA ICOM-1577 Begin:Add by b.jiang C01063 2015-07-17
		SDKEvent.addStaticEventListener(ICatchEventID.ICH_EVENT_SDCARD_REMOVED);
		// JIRA ICOM-1577 End:Add by b.jiang C01063 2015-07-17

		camSlotListView = (ListView) findViewById(R.id.cam_slot_listview);

		// JIRA ICOM-1878 Start:Add by b.jiang 2015-08-31
		camSlotListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "camSlotListView.setOnItemClickListener arg2=" + arg2);

				if (arg2 == 0) {
					connectProgress("slot1");
				} else if (arg2 == 1) {
					connectProgress("slot2");
				} else if (arg2 == 2) {
					connectProgress("slot3");
				}
			}

		});

		camSlotListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "camSlotListView.setOnItemLongClickListener arg2=" + arg2);
				if (arg2 == 0) {
					Cursor cursor = CameraSlotSQLite.getInstance().query("slot1");
					if (cursor.getCount() > 0) {
						showSlotLongClickOptionDialog("slot1");
					}

				} else if (arg2 == 1) {
					Cursor cursor = CameraSlotSQLite.getInstance().query("slot2");
					if (cursor.getCount() > 0) {
						showSlotLongClickOptionDialog("slot2");
					}
				} else if (arg2 == 2) {
					Cursor cursor = CameraSlotSQLite.getInstance().query("slot3");
					if (cursor.getCount() > 0) {
						showSlotLongClickOptionDialog("slot3");
					}
				}
				return true;
			}

		});

		GlobalInfo.getInstance().startScreenListener();

		//add by lihaiping1603@aliyun.com on 2016-12-26
		ActivityCollector.addActivity(this);

		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "end oncreate");
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		if (SystemCheckTools.isApplicationSentToBackground(AppStartActivity.this) == true) {
			Log.d("tigertiger", "onStop......destroy the app");
			ExitApp.getInstance().exit();
		}
		super.onStop();
	}

	private final Handler appStartHandler = new Handler() {

		public void handleMessage(Message msg) {
			Log.e("AppStart", "what =  " + msg.what);
			switch (msg.what) {
			case GlobalInfo.MESSAGE_DELETE_CAMERA:
				WriteLogToDevice.writeLog("[Normal] -- Main: ", "receive MESSAGE_DELETE_CAMERA power =" + msg.obj);

				int arg = (Integer) msg.obj;

				if (arg == 0) {
					Cursor cursor = CameraSlotSQLite.getInstance().query("slot1");
					if (cursor.getCount() > 0) {
						showSlotLongClickOptionDialog("slot1");
					}

				} else if (arg == 1) {
					Cursor cursor = CameraSlotSQLite.getInstance().query("slot2");
					if (cursor.getCount() > 0) {
						showSlotLongClickOptionDialog("slot2");
					}
				} else if (arg == 2) {
					Cursor cursor = CameraSlotSQLite.getInstance().query("slot3");
					if (cursor.getCount() > 0) {
						showSlotLongClickOptionDialog("slot3");
					}
				}
				break;

			case CONNECTING:
				if (progressDialog==null) {
					progressDialog = new ProgressDialog(AppStartActivity.this);
					progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					progressDialog.setMessage(AppStartActivity.this.getString(R.string.action_processing));
					progressDialog.setCancelable(false);
					progressDialog.show();
				}
				break;
			case CONNECT_SUCCESS:
				WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "CONNECT_SUCCESS");
				if (progressDialog!=null)
					progressDialog.dismiss();
				redirectToMain();
				break;
			case CONNECT_FAIL:
				WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "CONNECT_FAIL");
				if (progressDialog!=null)
					progressDialog.dismiss();
				redirectToExit();
				break;
			case CONNECT_NEW_WIFI_SUCCESS:
				WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "receive CONNECT_NEW_WIFI_SUCCESS");
				if (progressDialog==null) {
					progressDialog = new ProgressDialog(AppStartActivity.this);
					progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					progressDialog.setMessage(AppStartActivity.this.getString(R.string.action_processing));
					progressDialog.setCancelable(false);
					progressDialog.show();
				}
				//initAPP(cfgConvertWifi.SSID);
				initAPP();
				break;
			case NO_WIFI_CONNECTTED:
				WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "NO_WIFI_CONNECTTED");
				redirectToExit();
				break;
			case GlobalInfo.MESSAGE_GET_NEW_CAMERA:
				WriteLogToDevice.writeLog("[Normal] -- AppStartActivity: ", "Recv message MESSAGE_GET_NEW_CAMERA");
				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				if (optionDialog != null) {
					optionDialog.dismiss();
				}
				if (searchTimer != null) {
					searchTimer.cancel();
				}
				CameraSelectedInfo temp = (CameraSelectedInfo) msg.obj;

				// Log.d("1111", "searchCameraInfoList.size()=" +
				// searchCameraInfoList.size());
				// if (searchCameraInfoList.size() == 0) {
				searchCameraInfoList.addLast(new SelectedCameraInfo(temp.cameraName, temp.cameraIp, temp.cameraMode, temp.uid));
				// showsearchCameraInfoListDialog();
				showsearchCameraInfoListSingleDialog();
				// return;
				// }
				break;
			case GlobalInfo.MESSAGE_CAMERA_SEARCH_SELECTED:
				SDKSession.stopDeviceScan();
				if (scanCameraListener != null) {
					SDKEvent.delScanEventListener(scanCameraListener);
				}
				// connect the camera
				SelectedCameraInfo temp1 = (SelectedCameraInfo) msg.obj;
				Log.d("1111", "temp.cameraIp=" + temp1.cameraIp);

				initAPPByIp(temp1.cameraIp);
				break;

			case GlobalInfo.MESSAGE_CAMERA_SCAN_TIME_OUT:

				SDKSession.stopDeviceScan();
				if (scanCameraListener != null) {
					SDKEvent.delScanEventListener(scanCameraListener);
				}

				WriteLogToDevice.writeLog("[ERROR] -- AppStartActivity: ", "startDeviceScan CAMERA_SCAN_TIME_OUT");
				if (optionDialog != null) {
					optionDialog.dismiss();
				}
				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				showWarningDilaog(getResources().getString(R.string.alert_no_camera_found));
				break;
			}
		};
	};
	public MyCamera currentCamera;
	private Timer searchTimer;
	private ProgressDialog progressDialog=null;
	private AlertDialog optionDialog;

	private void redirectToMain() {
		WifiManager mWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = mWifi.getConnectionInfo();
		GlobalInfo.getInstance().setSsid(wifiInfo.getSSID());
		Intent intent = new Intent(this, Main.class);
		startActivity(intent);
	}

	private void redirectToExit() {
//		AlertDialog.Builder builder = new AlertDialog.Builder(AppStartActivity.this);
//		builder.setMessage(AppStartActivity.this.getString(R.string.dialog_timeout));
//		builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
//
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				dialog.dismiss();
//				// ExitApp.getInstance().exit()
////				camSlotListView.setEnabled(true);
//			}
//		});
//		AlertDialog dialog = builder.create();
//		dialog.setCancelable(false);
//		dialog.show();
		//add by lihaiping1603@aliyun.com on 2016-12-26
		//ActivityCollector.finishAll();

		//启动网络选择界面
		Intent intent = new Intent();
		intent.setClass(AppStartActivity.this, LHPWifiConnectActivity.class);
		startActivity(intent);

		Log.d("AppStart", "dialog.show()");

	}

	private void sendOkMsg(int what) {
		appStartHandler.obtainMessage(what).sendToTarget();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
			case KeyEvent.KEYCODE_1://搜索
				Intent intent = new Intent();
				intent.setClass(AppStartActivity.this, LHPWifiConnectActivity.class);
				startActivity(intent);
				break;
 			case KeyEvent.KEYCODE_2://
				ActivityCollector.finishAll();
				break;
			default:
				return super.onKeyDown(keyCode, event);
		}
		return true;
	}

	@Override
	protected void onStart() {
		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "begin onStart");
		// TODO Auto-generated method stub
		super.onStart();
//		initCamSlotList();
//		DisplayMetrics metrics = new DisplayMetrics();
//		getWindowManager().getDefaultDisplay().getMetrics(metrics);
//		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "onStart Height=" + metrics.heightPixels);
//		myListViewAdapter = new CameraSlotAdapter(this, camSlotList, metrics.heightPixels, appStartHandler);
//		camSlotListView.setAdapter(myListViewAdapter);
//
//		camSlotListView.setEnabled(true);
//		CameraSlotSQLite.getInstance().setCurrentCamSsid(null);
//		CameraSlotSQLite.getInstance().setCurrentSlotName(null);
		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "end onStart");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "begin onResume()");
		super.onResume();
//		GlobalInfo.getInstance().setCurrentApp(AppStartActivity.this);
//		UserMacPermition.initUserMacPermition();
//
//		DisplayMetrics dm = new DisplayMetrics();
//		this.getWindowManager().getDefaultDisplay().getMetrics(dm);

		//add by lhp for test is ok
//		connectProgress("slot1");

		//add by lihaiping1603@aliyun.com on 2016-12-26 start
		wifiOperation();
		//add by lihaiping1603@aliyun.com on 2016-12-26 end

	}

	/**
	 * 
	 * Added by zhangyanhu C01012,2014-4-3
	 */
	public void enableSDKLog() {
		String path = null;
		path = Environment.getExternalStorageDirectory().toString() + "/IcatchSportCamera_SDK_Log";
		Environment.getExternalStorageDirectory();
		//这个api开debugMode，true是开，false是关，默认是关;
//		ICatchWificamLog.getInstance().setDebugMode(true);
		ICatchWificamLog.getInstance().setFileLogPath(path);
		
		Log.d("AppStart", "path: " + path);
		if (path != null) {
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
		}
		ICatchWificamLog.getInstance().setSystemLogOutput(true);
		ICatchWificamLog.getInstance().setFileLogOutput(true);
		ICatchWificamLog.getInstance().setRtpLog(true);
		ICatchWificamLog.getInstance().setPtpLog(true);
		ICatchWificamLog.getInstance().setRtpLogLevel(ICatchLogLevel.ICH_LOG_LEVEL_INFO);
		ICatchWificamLog.getInstance().setPtpLogLevel(ICatchLogLevel.ICH_LOG_LEVEL_INFO);
	}

	private void initAPP() {
		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "isWifiConnect() == true");
		currentCamera = new MyCamera();
		if (currentCamera.getSDKsession().prepareSession() == false) {
			// progressBar.setVisibility(View.GONE);
			// redirectToExit();
			appStartHandler.obtainMessage(CONNECT_FAIL).sendToTarget();
			return;
		}
		if (currentCamera.getSDKsession().checkWifiConnection() == true) {
			GlobalInfo.getInstance().addCamera(currentCamera);
			GlobalInfo.getInstance().setCurrentCamera(currentCamera);
			currentCamera.initCamera();
			if (CameraProperties.getInstance().hasFuction(PropertyId.CAMERA_DATE)) {
				long time = System.currentTimeMillis();
				Date date = new Date(time);
				SimpleDateFormat myFmt = new SimpleDateFormat("yyyyMMdd HHmmss");
				String temp = myFmt.format(date);
				temp = temp.replaceAll(" ", "T");
				temp = temp + ".0";
				CameraProperties.getInstance().setCameraDate(temp);
			}
			currentCamera.setMyMode(1);
			appStartHandler.obtainMessage(CONNECT_SUCCESS).sendToTarget();

			return;
		} else {
			WriteLogToDevice.writeLog("[ERROR] -- AppStartActivity: ", "..........checkWifiConnection  fail");
			appStartHandler.obtainMessage(CONNECT_FAIL).sendToTarget();
			return;
		}
	}

	private void initAPPByIp(String ip) {
		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "isWifiConnect() == true");
		// progressBar.setVisibility(View.VISIBLE);
		currentCamera = new MyCamera();
		if (currentCamera.getSDKsession().prepareSession(ip) == false) {
			// progressBar.setVisibility(View.GONE);
			// redirectToExit();
			appStartHandler.obtainMessage(CONNECT_FAIL).sendToTarget();
			return;
		}
		if (currentCamera.getSDKsession().checkWifiConnection() == true) {
			GlobalInfo.getInstance().addCamera(currentCamera);
			GlobalInfo.getInstance().setCurrentCamera(currentCamera);
			currentCamera.initCamera();
			if (CameraProperties.getInstance().hasFuction(PropertyId.CAMERA_DATE)) {
				long time = System.currentTimeMillis();
				Date date = new Date(time);
				SimpleDateFormat myFmt = new SimpleDateFormat("yyyyMMdd HHmmss");
				String temp = myFmt.format(date);
				temp = temp.replaceAll(" ", "T");
				temp = temp + ".0";
				CameraProperties.getInstance().setCameraDate(temp);
			}
			currentCamera.setMyMode(1);
			appStartHandler.obtainMessage(CONNECT_SUCCESS).sendToTarget();

			return;
		} else {
			WriteLogToDevice.writeLog("[ERROR] -- AppStartActivity: ", "..........checkWifiConnection  fail");
			appStartHandler.obtainMessage(CONNECT_FAIL).sendToTarget();
			return;
		}
	}

	private void connectNewWifi(final WifiSsidPwd wifiSsidPwd, ScanResult converWifi) {
		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "connectOtherWifi");
		wifiCheck.connectWifi(wifiSsidPwd.ssid, wifiSsidPwd.pwd, wifiCheck.getSecurity(converWifi));
		reconnectTime = 0;
		final Timer connectTimer = new Timer();
		TimerTask task = new TimerTask() {

			@Override
			public void run() {
				if (wifiCheck.isWifiConnected(AppStartActivity.this, wifiSsidPwd.ssid) == true) {
					WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "isWifiConnect() == true");
					sendOkMsg(CONNECT_NEW_WIFI_SUCCESS);
					if (connectTimer != null) {
						connectTimer.cancel();
					}
					return;
				} else {
					WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "isWifiConnect() == false  reconnectTime =" + reconnectTime);
					reconnectTime++;
					if (reconnectTime >= RETRY_TIMES) {
						if (connectTimer != null) {
							connectTimer.cancel();
						}
						wifiList.remove(0);
						sendOkMsg(NO_WIFI_CONNECTTED);
						return;
					}
				}
			}
		};
		connectTimer.schedule(task, 0, 3000);
	}

	public void saveSsidAndPassword(String ssid, String password) {
		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "saveSsidAndPassword ssid =" + ssid + "  password=" + password);
		FileOutputStream outStream = null;
		String tempSsid = null;
		String tempPassword = null;
		try {
			outStream = openFileOutput("ssidAndPassword.txt", Context.MODE_PRIVATE);
			tempSsid = ssid + ";";
			tempPassword = password + ";";
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			WriteLogToDevice.writeLog("[Error] -- Appstart: ", "open outStream  FileNotFoundException");
			e.printStackTrace();
		}

		try {
			outStream.write(tempSsid.getBytes());
			outStream.write(tempPassword.getBytes());
			outStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			WriteLogToDevice.writeLog("[Error] -- Appstart: ", "open outStream IOException");
			e.printStackTrace();
		}
		// outStream.
	}

	public String[] readSsidAndPassword() {
		// outStream.
		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "start readSsidAndPassword");
		FileInputStream inStream = null;
		try {
			inStream = openFileInput("ssidAndPassword.txt");
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block`
			WriteLogToDevice.writeLog("[Error] -- Appstart: ", "FileNotFoundException");
			e1.printStackTrace();
		}
		if (inStream == null) {

			return null;
		}
		try {
			if (inStream.available() <= 0) {
				return null;
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		byte[] b = null;
		try {
			b = new byte[inStream.available()];
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 新建一个字节数组
		try {
			inStream.read(b);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// 将文件中的内容读取到字节数组中
		try {
			inStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (b == null) {
			return null;
		}
		String str2 = new String(b);// 再将字节数组中的内容转化成字符串形式输出
		if (str2 == null) {
			return null;
		}
		String newStr = str2.replaceAll("\"", "");
		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "------newStr =" + newStr);
		String[] temp = newStr.split(";");
		if (temp.length % 2 != 0) {
			return null;
		}
		String[] ssidAndPsd = new String[2];

		for (int ii = 0; ii < 1; ii = ii + 2) {

		}
		ssidAndPsd[0] = temp[0];
		ssidAndPsd[1] = temp[1];
		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "end readSsidAndPassword ssid =" + ssidAndPsd[0] + "  password=" + ssidAndPsd[1]);
		return ssidAndPsd;

	}

	public String getLocalMacAddress() {
		WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "current Mac=" + info.getMacAddress().toLowerCase());
		return info.getMacAddress().toLowerCase();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// JIRA ICOM-1577 Begin:Add by b.jiang C01063 2015-07-17
		SDKEvent.delStaticEventListener(ICatchEventID.ICH_EVENT_SDCARD_REMOVED);
		// JIRA ICOM-1577 End:Add by b.jiang C01063 2015-07-17
		CameraSlotSQLite.getInstance().closeDB();
		//add by lihaiping1603@aliyun.com on 2016-12-26
		ActivityCollector.removeActivity(this);
	}

	public class ScanCameraListener implements ICatchWificamListener {
		@Override
		public void eventNotify(ICatchEvent arg0) {
			// TODO Auto-generated method stub
			WriteLogToDevice.writeLog("[Normal] -- AppStartActivity: ", "Send..........MESSAGE_GET_NEW_CAMERA");
			Log.d("1111", "get a uid arg0.getgetStringValue3() ==" + arg0.getStringValue3());
			if (arg0.getIntValue1() == 1) {// ap mode
				return;
			}
			appStartHandler.obtainMessage(GlobalInfo.MESSAGE_GET_NEW_CAMERA,
					new CameraSelectedInfo(arg0.getStringValue2(), arg0.getStringValue1(), arg0.getIntValue1(), arg0.getStringValue3())).sendToTarget();
		}
	}

	private void startSearchTimeoutTimer() {
		searchTimer = new Timer();
		TimerTask searchTask = new TimerTask() {
			@Override
			public void run() {
				appStartHandler.obtainMessage(GlobalInfo.MESSAGE_CAMERA_SCAN_TIME_OUT).sendToTarget();
			}
		};
		searchTimer.schedule(searchTask, 10000);
	}

	private void showProgressDialog(String message) {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
		progressDialog = new ProgressDialog(AppStartActivity.this);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		// progressDialog =
		// CustomProgressDialog.createDialog(MainActivity.this);
		progressDialog.setMessage(message);
		progressDialog.setCancelable(false);
		progressDialog.show();
	}

	private void showsearchCameraInfoListSingleDialog() {
		if (searchCameraInfoList.isEmpty()) {
			return;
		}
		CharSequence title = "Please select camera";
		final CharSequence[] tempsearchCameraInfoList = new CharSequence[searchCameraInfoList.size()];

		for (int ii = 0; ii < tempsearchCameraInfoList.length; ii++) {
			if (searchCameraInfoList.get(ii).cameraMode == 2) {
				tempsearchCameraInfoList[ii] = searchCameraInfoList.get(ii).cameraName + "\n" + searchCameraInfoList.get(ii).cameraIp + "          "
						+ "Station";
				continue;
			}
			if (searchCameraInfoList.get(ii).cameraMode == 1) {
				tempsearchCameraInfoList[ii] = searchCameraInfoList.get(ii).cameraName + "\n" + searchCameraInfoList.get(ii).cameraIp + "          " + "AP";
				continue;
			}

			if (searchCameraInfoList.get(ii).cameraMode == 3) {
				tempsearchCameraInfoList[ii] = searchCameraInfoList.get(ii).cameraName + "\n" + searchCameraInfoList.get(ii).cameraIp + "          "
						+ "Ethernet";
				continue;
			}
		}

		DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				// searchCameraInfoList.get(which)
				appStartHandler.obtainMessage(GlobalInfo.MESSAGE_CAMERA_SEARCH_SELECTED, searchCameraInfoList.get(which)).sendToTarget();
				optionDialog.dismiss();
			}
		};
		showOptionDialogSingle(title, tempsearchCameraInfoList, 0, listener, true);
	}

	private void showOptionDialogSingle(CharSequence title, CharSequence[] items, int checkedItem, DialogInterface.OnClickListener listener, boolean cancelable) {
		if (optionDialog == null || optionDialog.isShowing() == false) {
			optionDialog = new AlertDialog.Builder(AppStartActivity.this).setTitle(title).setSingleChoiceItems(items, checkedItem, listener).create();
			optionDialog.setCancelable(cancelable);
			optionDialog.show();
		}
	}

	private void showWarningDilaog(String message) {
//		AlertDialog.Builder ad1 = new AlertDialog.Builder(AppStartActivity.this);
//		ad1.setTitle(message);
//		ad1.setIcon(android.R.drawable.ic_dialog_info);
//		ad1.setCancelable(true);
//		ad1.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
//			public void onClick(DialogInterface dialog, int arg1) {
//				dialog.dismiss();
//			}
//		});
//		ad1.show();
	}

	private class SelectedCameraInfo {
		public String cameraName;
		public String cameraIp;
		public int cameraMode;
		public String password;
		public String uid;

		public SelectedCameraInfo(String cameraName, String cameraIp, int cameraMode, String uid) {
			this.cameraName = cameraName;
			this.cameraIp = cameraIp;
			this.cameraMode = cameraMode;
			this.uid = uid;
		}
	}

	private void showDialog(String message) {
//		AlertDialog.Builder builder = new AlertDialog.Builder(AppStartActivity.this);
//		// builder.setMessage(AppStartActivity.this.getString(R.string.dialog_timeout));
//		builder.setMessage(message);
//		builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
//
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				dialog.dismiss();
//				// ExitApp.getInstance().exit()
//				camSlotListView.setEnabled(true);
//			}
//		});
//		AlertDialog dialog = builder.create();
//		dialog.setCancelable(false);
//		dialog.show();
	}

	private void connectProgress(String slotName) {
		final String curSlotName = slotName;
		WifiManager mWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = mWifi.getConnectionInfo();
		final String wifiSsid = wifiInfo.getSSID().replaceAll("\"", "");
		// wifiSsid = wifiSsid.replaceAll("\"", "");
		final String currentCamSsid;
		boolean isSlotRegister = false;
		Cursor cursor = CameraSlotSQLite.getInstance().query(slotName);
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			isSlotRegister = true;
			currentCamSsid = cursor.getString(cursor.getColumnIndex("cname"));
		} else {
			isSlotRegister = false;
			currentCamSsid = "";
		}

		WriteLogToDevice.writeLog("[Normal] -- AppStartActivity: ", "wifiSsid = " + wifiSsid);
		WriteLogToDevice.writeLog("[Normal] -- AppStartActivity: ", "currentCamSsid = " + currentCamSsid);
		if (wifiSsid == "" || wifiSsid == null || wifiSsid.contains("unknown ssid")) {
			showDialog("Please connent camera wifi " + currentCamSsid);
			return;
		}
		// 判断插槽是否被注册
		// 未注册
		if (!isSlotRegister) {
			Cursor corsor = CameraSlotSQLite.getInstance().queryCamName(wifiSsid);
			if (corsor.getCount() > 0) {
				showDialog("Camera " + wifiSsid + " has been registered");
			} else {
				// showDialog("reconnect camera");
				appStartHandler.obtainMessage(CONNECTING).sendToTarget();
				new Thread(new Runnable() {
					public void run() {
						connectCam(curSlotName, wifiSsid);
					}
				}).start();
				// connectCam(slotName,wifiSsid);
			}

		}
		// 已注册
		else {
			if (wifiSsid.equals(currentCamSsid)) {
				// showDialog("connect camera");
				appStartHandler.obtainMessage(CONNECTING).sendToTarget();
				new Thread(new Runnable() {
					public void run() {
						connectCam(curSlotName, currentCamSsid);
					}
				}).start();
				// connectCam(slotName,currentCamSsid);
			} else {
				showDialog("Please connect camera wifi " + currentCamSsid);
			}
		}

	}

	private void connectCam(String slotName, String ssid) {

		WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "connectCam isWifiConnect() == true");
		currentCamera = new MyCamera();
		if (currentCamera.getSDKsession().prepareSession() == false) {
			appStartHandler.obtainMessage(CONNECT_FAIL).sendToTarget();
			return;
		}
		if (currentCamera.getSDKsession().checkWifiConnection() == true) {
			GlobalInfo.getInstance().addCamera(currentCamera);
			GlobalInfo.getInstance().setCurrentCamera(currentCamera);
			currentCamera.initCamera();
			if (CameraProperties.getInstance().hasFuction(PropertyId.CAMERA_DATE)) {
				long time = System.currentTimeMillis();
				Date date = new Date(time);
				SimpleDateFormat myFmt = new SimpleDateFormat("yyyyMMdd HHmmss");
				String temp = myFmt.format(date);
				temp = temp.replaceAll(" ", "T");
				temp = temp + ".0";
				CameraProperties.getInstance().setCameraDate(temp);
			}
			currentCamera.setMyMode(1);

			CameraSlotSQLite.getInstance().setCurrentCamSsid(ssid);
			CameraSlotSQLite.getInstance().setCurrentSlotName(slotName);

			appStartHandler.obtainMessage(CONNECT_SUCCESS).sendToTarget();

			return;
		} else {
			WriteLogToDevice.writeLog("[ERROR] -- AppStartActivity: ", "..........checkWifiConnection  fail");
			appStartHandler.obtainMessage(CONNECT_FAIL).sendToTarget();
			return;
		}

	}

	// JIRA ICOM-1878 Start:Add by b.jiang 2015-08-31
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		WriteLogToDevice.writeLog("[Normal] -- AppStartActivity: ", "strart onRestart()");
		super.onRestart();
		WriteLogToDevice.writeLog("[Normal] -- AppStartActivity: ", "end onRestart()");
	}

	private void initCamSlotList() {
		WriteLogToDevice.writeLog("[Normal] -- AppStartActivity: ", "strart initCamSlotList");
		if (camSlotList != null) {
			camSlotList.clear();
			camSlotList = null;

		}
		camSlotList = new ArrayList<CameraSlot>();

		WifiManager mWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = mWifi.getConnectionInfo();
		String wifiSsid = wifiInfo.getSSID();
		wifiSsid = wifiSsid.replaceAll("\"", "");
		Log.d("0910", "strart initCamSlotList wifiInfo=" + wifiInfo);
		Log.d("0910", "strart initCamSlotList wifiInfo.getSSID()=" + wifiInfo.getSSID());
		Log.d("0910", "strart initCamSlotList wifiSsid=" + wifiSsid);
		Cursor cursor = CameraSlotSQLite.getInstance().query("slot1");
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			CameraSlot camSlotItem = new CameraSlot("slot1", false, null, null, false);
			String camName = cursor.getString(cursor.getColumnIndex("cname"));
			byte[] imageBuf = cursor.getBlob(cursor.getColumnIndex("imagebuffer"));
			camSlotItem.isOccupied = true;
			camSlotItem.cameraName = camName;
			camSlotItem.cameraPhoto = imageBuf;
			if (camName.equals(wifiSsid)) {
				camSlotItem.enableConnect = true;
			} else {
				camSlotItem.enableConnect = false;
			}
			camSlotList.add(camSlotItem);
		} else {
			CameraSlot camSlotItem = new CameraSlot("slot1", false, null, null, false);
			camSlotList.add(camSlotItem);
		}
		cursor = CameraSlotSQLite.getInstance().query("slot2");
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			CameraSlot camSlotItem = new CameraSlot("slot2", false, null, null, false);
			String camName = cursor.getString(cursor.getColumnIndex("cname"));
			byte[] imageBuf = cursor.getBlob(cursor.getColumnIndex("imagebuffer"));
			camSlotItem.isOccupied = true;
			camSlotItem.cameraName = camName;
			camSlotItem.cameraPhoto = imageBuf;
			if (camName.equals(wifiSsid)) {
				camSlotItem.enableConnect = true;
			} else {
				camSlotItem.enableConnect = false;
			}
			camSlotList.add(camSlotItem);
		} else {
			CameraSlot camSlotItem = new CameraSlot("slot2", false, null, null, false);
			camSlotList.add(camSlotItem);
		}

		cursor = CameraSlotSQLite.getInstance().query("slot3");
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			CameraSlot camSlotItem = new CameraSlot("slot3", false, null, null, false);
			String camName = cursor.getString(cursor.getColumnIndex("cname"));
			byte[] imageBuf = cursor.getBlob(cursor.getColumnIndex("imagebuffer"));
			camSlotItem.isOccupied = true;
			camSlotItem.cameraName = camName;
			camSlotItem.cameraPhoto = imageBuf;
			if (camName.equals(wifiSsid)) {
				camSlotItem.enableConnect = true;
			} else {
				camSlotItem.enableConnect = false;
			}
			camSlotList.add(camSlotItem);
		} else {
			CameraSlot camSlotItem = new CameraSlot("slot3", false, null, null, false);
			camSlotList.add(camSlotItem);
		}

		WriteLogToDevice.writeLog("[Normal] -- AppStartActivity: ", "end initCamSlot");

	}

	private void showSlotLongClickOptionDialog(String slotName) {
//		final String sName = slotName;
//		final CharSequence[] items = { "Delete", "Cancel" };
//		Dialog dialog = null;
//		Builder builder = new android.app.AlertDialog.Builder(this);
//		// 设置对话框的图标
//		builder.setIcon(R.drawable.delete);
//		// 设置对话框的标题
//		builder.setTitle("Camera");
//		// 添加按钮，android.content.DialogInterface.OnClickListener.OnClickListener
//		builder.setItems(items, new DialogInterface.OnClickListener() {
//
//			@Override
//			public void onClick(DialogInterface arg0, int arg1) {
//				if (items[arg1].equals("Delete")) {
//					CameraSlotSQLite.getInstance().delete(sName);
//					initCamSlotList();
//					DisplayMetrics metrics = new DisplayMetrics();
//					getWindowManager().getDefaultDisplay().getMetrics(metrics);
//					myListViewAdapter = new CameraSlotAdapter(AppStartActivity.this, camSlotList, metrics.heightPixels, appStartHandler);
//					camSlotListView.setAdapter(myListViewAdapter);
//				}
//
//				// WriteLogToDevice.writeLog("[Normal] -- showOptionDialog: ",
//				// "click "+items[arg1]);
//			}
//
//		});
//
//		dialog = builder.create();
//		dialog.show();
	}

	// JIRA ICOM-1878 End by b.jiang 2015-08-31


	//add by by lihaiping1603@aliyun.com on 2016-12-26 start
	private boolean wifiOperation(){
		if (wifiCheck==null){
			wifiCheck= new WifiCheck();
		}
		//打开wifi
		wifiCheck.openWifi();

		//这是写死指定链接的设备进行调试
//		if (wifiCheck.isWifiConnected(AppStartActivity.this,strWifiSSID) == true) {
//			WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "isWifiConnect() == true");
//			new Thread(new Runnable() {
//				public void run() {
//					appStartHandler.obtainMessage(CONNECT_NEW_WIFI_SUCCESS).sendToTarget();
//				}
//			}).start();
//			return true;
//		} else {
//			WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "isWifiConnect() == false  reconnectTime =" + reconnectTime);
//			//扫描
//			wifiCheck.startScan();
//			//
//			ScanResult destWifiResult=wifiCheck.hasThisWifi(strWifiSSID);
//			if (destWifiResult==null){
//				Log.d(TAG, "wifiOperation: not this wifi.");
//				new Thread(new Runnable() {
//					public void run() {
//						appStartHandler.obtainMessage(NO_WIFI_CONNECTTED).sendToTarget();
//					}
//				}).start();
//				return false;
//			}
//			WifiSsidPwd wifiSsidPwd=new WifiSsidPwd(strWifiSSID,strWifiPwd);
//			cfgConvertWifi=destWifiResult;
//			//appStartHandler.obtainMessage(CONNECTING).sendToTarget();
//			new Thread(new Runnable() {
//				public void run() {
//					appStartHandler.obtainMessage(CONNECTING).sendToTarget();
//				}
//			}).start();
//			connectNewWifi(wifiSsidPwd,destWifiResult);
//			return false;
//		}


		///////////////////////////////////////
		//改为如果链接，就直接打开链接的设备，如果没有，就显示可链接的wifi
		if(wifiCheck.isWifiConnect(AppStartActivity.this)==true){
			WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "isWifiConnect() == true");
			new Thread(new Runnable() {
				public void run() {
					appStartHandler.obtainMessage(CONNECT_NEW_WIFI_SUCCESS).sendToTarget();
				}
			}).start();

			return true;
		} else {
			WriteLogToDevice.writeLog("[Normal] -- Appstart: ", "isWifiConnect() == false  reconnectTime =" + reconnectTime);
			Intent intent = new Intent();
			intent.setClass(AppStartActivity.this, LHPWifiConnectActivity.class);
			startActivity(intent);
			return false;
		}
	}
	///add by by lihaiping1603@aliyun.com on 2016-12-26 end

}
